package 结构型模式.组合模式.demo01.engine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import 结构型模式.组合模式.demo01.logic.LogicFilter;
import 结构型模式.组合模式.demo01.model.TreeRich;
import 结构型模式.组合模式.demo01.model.vo.EngineResult;
import 结构型模式.组合模式.demo01.model.vo.TreeNode;
import 结构型模式.组合模式.demo01.model.vo.TreeRoot;

import java.util.Map;

/**
 * 提供决策树流程的处理过程，有点像通过链路的关系( 性别 、 年龄 )在二叉树中寻找果实节点的过程。
 *
 * @author Eric
 */
public abstract class EngineBase extends EngineConfig implements IEngine {
    private Logger logger = LoggerFactory.getLogger(EngineBase.class);

    /**
     * @param treeId
     * @param userId
     * @param treeRich
     * @param decisionMatter
     * @return
     */
    @Override
    public abstract EngineResult process(Long treeId, String userId, TreeRich treeRich, Map<String, String> decisionMatter);

    protected TreeNode engineDecisionMaker(TreeRich treeRich, Long treeId,
                                           String userId, Map<String, String> decisionMatter) {
        TreeRoot treeRoot = treeRich.getTreeRoot();
        Map<Long, TreeNode> treeNodeMap = treeRich.getTreeNodeMap();
        // 规则树根ID
        Long rootNodeId = treeRoot.getTreeRootNodeId();
        TreeNode treeNodeInfo = treeNodeMap.get(rootNodeId);
        // 节点类型[NodeType]； 1子叶、 2果实
        while (treeNodeInfo.getNodeType().equals(1)) {
            String ruleKey = treeNodeInfo.getRuleKey();
            LogicFilter logicFilter = logicFilterMap.get(ruleKey);
            String matterValue = logicFilter.matterValue(treeId, userId,
                    decisionMatter);
            Long nextNode = logicFilter.filter(matterValue,
                    treeNodeInfo.getTreeNodeLinkList());
            treeNodeInfo = treeNodeMap.get(nextNode);
            logger.info("决策树引擎=>{} userId： {} treeId： {} treeNode： {} ruleKey： {}  matterValue：{} ",
                    treeRoot.getTreeName(), userId, treeId, treeNodeInfo.getTreeNodeId(), ruleKey, matterValue);
        }

        return treeNodeInfo;
    }
}